{% extends "base.html" %}

{% block title %}TestBrain - 文件解析{% endblock %}

{% block extra_css %}
<style>
    .upload-container {
        margin: 20px;
        padding: 20px;
    }
    
    .upload-area {
        border: 2px dashed #ddd;
        border-radius: 8px;
        padding: 60px 40px;
        text-align: center;
        background-color: #f8f9fa;
        margin: 30px 0;
        min-height: 300px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
    }

    .upload-area:hover {
        border-color: #007bff;
        background-color: #f1f7ff;
    }

    .file-input-button {
        padding: 12px 30px;
        font-size: 16px;
        margin-bottom: 20px;
    }

    .upload-hint {
        color: #666;
        font-size: 14px;
        margin-top: 15px;
    }

    .submit-container {
        text-align: center;
        margin-top: 20px;
    }

    .submit-button {
        padding: 12px 40px;
        font-size: 16px;
    }

    .selected-file {
        margin-top: 15px;
        color: #28a745;
        font-weight: 500;
        display: none;  /* 初始状态隐藏 */
    }

    /* 新增的表格样式 */
    .result-table {
        margin-top: 30px;
        display: none;
    }

    .result-table table {
        width: 100%;
        border-collapse: collapse;
    }

    .result-table th, .result-table td {
        border: 1px solid #dee2e6;
        padding: 12px;
    }

    .result-table th {
        background-color: #f8f9fa;
        font-weight: 600;
    }

    .result-table .scenario-row {
        background-color: #f8f9fa;
    }

    .priority-high {
        color: #dc3545;
    }

    .priority-medium {
        color: #ffc107;
    }

    .priority-low {
        color: #28a745;
    }

    .summary-section {
        margin-top: 20px;
        padding: 15px;
        background-color: #f8f9fa;
        border-radius: 5px;
    }
</style>
{% endblock %}

{% block content %}
<div class="upload-container">
    <h4 class="mb-4">测试点&测试场景解析</h4>
    <form method="post" enctype="multipart/form-data" id="uploadForm" onsubmit="return handleSubmit(event)">
        {% csrf_token %}
        <div class="upload-area">
            <input type="file" name="single_file" id="single_file" style="display: none;" onchange="updateFileName(this)">
            <button type="button" class="btn btn-primary file-input-button" onclick="document.getElementById('single_file').click()">
                选择要解析的文件
            </button>
            <div id="selected-file" class="selected-file"></div>
            <div id="uploadStatus" style="margin-top: 10px; color: #666;"></div>
            <div class="upload-hint">
                拖拽文件到此区域或点击选择文件,目前只支持docx文件<br>
                <span style="color: #dc3545;">Tips:从wiki导出的word默认是doc格式可使用wps手动转换一下</span>
            </div>
        </div>
        <div class="submit-container">
            <button type="submit" class="btn btn-success submit-button" id="submitBtn">开始解析</button>
        </div>
    </form>

    <!-- 新增的结果展示区域 -->
    <div id="resultTable" class="result-table">
        <h5>分析结果</h5>
        <div class="summary-section">
            <h6>统计信息</h6>
            <div id="summary" class="row">
                <!-- 统计信息将通过 JavaScript 填充 -->
            </div>
        </div>
        <table class="table table-bordered mt-3">
            <thead>
                <tr>
                    <th>测试点标题</th>
                    <th>测试点详细描述</th>
                    <th>优先级</th>
                    <th>测试场景详细描述</th>
                    <th>测试类型</th>
                </tr>
            </thead>
            <tbody id="resultTableBody">
                <!-- 结果将通过 JavaScript 填充 -->
            </tbody>
        </table>
    </div>
</div>

<script>
function updateFileName(input) {
    const selectedFile = document.getElementById('selected-file');
    if (input.files && input.files[0]) {
        selectedFile.style.display = 'block';
        selectedFile.textContent = '已选择文件: ' + input.files[0].name;
    } else {
        selectedFile.style.display = 'none';
        selectedFile.textContent = '';
    }
}

function displayResults(result) {
    const resultTable = document.getElementById('resultTable');
    const resultTableBody = document.getElementById('resultTableBody');
    const summaryDiv = document.getElementById('summary');

    // 清空现有内容
    resultTableBody.innerHTML = '';
    summaryDiv.innerHTML = '';

    // 显示统计信息
    const summary = result.summary;
    summaryDiv.innerHTML = `
        <div class="col-md-4">
            <p><strong>总测试点数：</strong>${summary.total_test_points}</p>
            <p><strong>总测试场景数：</strong>${summary.total_test_scenarios}</p>
        </div>
        <div class="col-md-8">
            <p><strong>高优先级测试点：</strong>${summary.high_priority_points}</p>
            <p><strong>中优先级测试点：</strong>${summary.medium_priority_points}</p>
            <p><strong>低优先级测试点：</strong>${summary.low_priority_points}</p>
        </div>
    `;

    // 填充测试点和场景数据
    result.test_points.forEach(point => {
        const scenariosCount = point.scenarios.length;
        
        point.scenarios.forEach((scenario, index) => {
            const row = document.createElement('tr');
            
            // 格式化场景描述，处理步骤和预期结果的换行
            const formattedDescription = scenario.description.split('\n').map(line => {
                if (line.trim().startsWith('预期结果：')) {
                    return `<div class="text-success mt-2"><strong>${line.trim()}</strong></div>`;
                } else if (line.trim().match(/^\d+\./)) {
                    return `<div class="mt-1">${line.trim()}</div>`;
                }
                return line;
            }).join('');
            
            if (index === 0) {
                // 第一行显示测试点信息，并合并行
                row.innerHTML = `
                    <td rowspan="${scenariosCount}">${point.title}</td>
                    <td rowspan="${scenariosCount}">${point.description}</td>
                    <td rowspan="${scenariosCount}" class="priority-${point.priority.toLowerCase()}">${point.priority}</td>
                    <td>${formattedDescription}</td>
                    <td>${scenario.test_type}</td>
                `;
            } else {
                // 其他行只显示场景信息
                row.innerHTML = `
                    <td>${formattedDescription}</td>
                    <td>${scenario.test_type}</td>
                `;
            }
            
            resultTableBody.appendChild(row);
        });
    });

    // 显示结果表格
    resultTable.style.display = 'block';
}

async function handleSubmit(event) {
    event.preventDefault();
    
    const form = event.target;
    const fileInput = form.querySelector('input[type="file"]');
    const submitBtn = document.getElementById('submitBtn');
    const statusDiv = document.getElementById('uploadStatus');
    
    if (!fileInput.files || !fileInput.files[0]) {
        statusDiv.textContent = '请先选择要上传的文件';
        statusDiv.style.color = '#dc3545';
        return false;
    }

    submitBtn.disabled = true;
    statusDiv.textContent = '文件解析中，请稍候...';
    statusDiv.style.color = '#dc3545';
    statusDiv.style.fontWeight = 'bold';

    try {
        const formData = new FormData(form);
        const response = await fetch(form.action, {
            method: 'POST',
            body: formData,
            headers: {
                'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
            }
        });

        const result = await response.json();

        if (result.success) {
            statusDiv.textContent = `文件解析成功！`;
            statusDiv.style.color = '#28a745';
            fileInput.value = '';
            document.getElementById('selected-file').style.display = 'none';
            
            // 显示分析结果
            displayResults(result.result);
        } else {
            statusDiv.textContent = result.error || '文件解析失败，请重试';
            statusDiv.style.color = '#dc3545';
        }
    } catch (error) {
        statusDiv.textContent = '文件解析过程中发生错误，请重试';
        statusDiv.style.color = '#dc3545';
    } finally {
        submitBtn.disabled = false;
    }

    return false;
}
</script>
{% endblock %}